<template>
  <div style="display: flex; flex-direction: row; height: auto">
    <div :style="{ width: leftPanelWidth + 'px' }">
      <el-scrollbar height="88vh">
        <el-tree
          ref="docTree"
          :data="treeData"
          node-key="label"
          default-expand-all
          :props="defaultProps"
          :highlight-current="true"
          :current-node-key="currentNodeKey"
          @current-change="onTreeCurrentChange"
        />
      </el-scrollbar>

      <div
        style="display: flex; flex-direction: row; margin-left: 15px"
        v-if="isManager"
      >
        <el-button
          :disabled="currentNodeKey == null || currentNodeKey.length == 0"
          @click="createDoc"
        >
          新增
        </el-button>
        <el-button :disabled="!isTableSelRevisable()" @click="reviseDoc">
          修订
        </el-button>
        <el-button :disabled="!isTableSelReleasable()" @click="createWorkflow">
          发起流程
        </el-button>
      </div>
    </div>
    <div class="resizer" @mousedown="startResize"></div>
    <div style="flex: 1">
      <div style="margin: 10px 10px 0px 10px">
        <div v-if="Number(selPaths?.length) > 0">
          <el-breadcrumb :separator-icon="ArrowRight">
            <el-breadcrumb-item @click="breadcrumbHandle('主页')">
              <div class="breadcrumb-link">主页</div>
            </el-breadcrumb-item>
            <el-breadcrumb-item
              v-for="(path, index) in selPaths"
              :key="index"
              @click="breadcrumbHandle(path)"
            >
              <div class="breadcrumb-link">{{ path }}</div>
            </el-breadcrumb-item>
          </el-breadcrumb>
        </div>
        <div v-else>未选择文档路径</div>
      </div>
      <el-divider style="margin-left: 10px" />
      <div
        style="
          margin: 10px;
          width: auto;
          display: flex;
          flex-direction: row;
          justify-content: space-between;
        "
      >
        <div
          style="
            display: flex;
            flex-direction: row;
            justify-content: flex-start;
            align-items: center;
            gap: 50px;
          "
        >
          <el-input
            v-model="input2"
            class="input-with-select"
            placeholder="输入关键词搜索"
            @keyup.enter="researchByFilterText"
            ><template #append>
              <el-button :icon="Search" @click="researchByFilterText" />
            </template>
          </el-input>
          <el-button @click="clearFilter">清除过滤</el-button>
          <el-checkbox-group v-model="checkedStatus" :min="1">
            <el-checkbox
              v-for="status in statusList"
              :key="status"
              :label="status"
              :value="status"
              size="large"
            >
              {{ status }}
            </el-checkbox>
          </el-checkbox-group>
        </div>
        <el-button :icon="Delete" @click="deleteSelData">删除</el-button>
      </div>
      <el-table
        ref="docTable"
        :data="currentPageTableData"
        highlight-current-row
        @current-change="onTableCurrentChange"
        table-layout="auto"
        @row-dblclick="rowDoubleClick"
        fit
        border
        style="width: auto"
        max-height="80vh"
        @filter-change="tableFilterChange"
      >
        <el-table-column type="index" label="序号" sortable width="60px" />
        <el-table-column label="查看" width="120px">
          <template #default="{ row }">
            <el-button
              link
              type="primary"
              size="small"
              @click="watchProps(row)"
            >
              属性
            </el-button>
            <!-- <el-button link type="primary" size="small" @click="watchContent(row)">附件</el-button> -->
            <el-button
              link
              type="primary"
              size="small"
              @click="openAttachmentData(row)"
            >
              附件
            </el-button>
          </template>
        </el-table-column>
        <el-table-column
          column-key="PP8_TITLE1"
          prop="PP8_TITLE1"
          show-overflow-tooltip
          label="标题1"
          width="120px"
          :filters="columnFilters.PP8_TITLE1"
        />
        <el-table-column
          column-key="PP8_TITLE2"
          prop="PP8_TITLE2"
          show-overflow-tooltip
          label="标题2"
          width="120px"
          :filters="columnFilters.PP8_TITLE2"
        />
        <el-table-column
          column-key="PP8_TITLE3"
          prop="PP8_TITLE3"
          show-overflow-tooltip
          label="标题3"
          width="160px"
          :filters="columnFilters.PP8_TITLE3"
        />
        <el-table-column
          column-key="PP8_TITLE4"
          show-overflow-tooltip
          prop="PP8_TITLE4"
          label="标题4"
          width="200px"
          :filters="columnFilters.PP8_TITLE4"
        />
        <el-table-column
          show-overflow-tooltip
          prop="PITEM_ID"
          label="管理番号"
          width="140px"
        />
        <el-table-column
          show-overflow-tooltip
          prop="PP8_TITLE4"
          label="文书名"
          width="140px"
        />
        <el-table-column
          show-overflow-tooltip
          prop="PITEM_REVISION_ID"
          label="版本"
          width="80px"
        />
        <!-- <el-table-column
          show-overflow-tooltip
          prop=""
          label="强制/推荐"
          width="100px"
        /> -->
        <el-table-column
          show-overflow-tooltip
          prop="PP8_UPDATEDATE"
          label="最终改定日"
          width="120px"
        />
        <el-table-column
          show-overflow-tooltip
          prop="RELEASED_STATUS"
          label="发布状态"
          width="100px"
        />
        <!-- <el-table-column
          show-overflow-tooltip
          prop="address"
          label="有效日期"
          width="120px"
        /> -->
      </el-table>
      <el-pagination
        layout="prev, pager, next"
        :total="total"
        :current-page="currentPage"
        :page-size="pageSize"
        :pager-count="11"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
  <el-drawer
    v-model="createDrawer"
    title="基准创建"
    direction="ltr"
    :show-close="false"
  >
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">基准创建</h4>
      <el-button type="primary" @click="submitCreateForm">确定</el-button>
      <el-button type="danger" @click="close">关闭</el-button>
    </template>
    <el-form
      :model="standardForm"
      label-width="100px"
      label-position="left"
      :rules="createFormRules"
      ref="standardFormRef"
    >
      <el-form-item label="附件 :" prop="filePath">
        <!-- <el-upload
          ref="uploadByCreate"
          class="upload-demo"
          :file-list="fileList"
          :before-upload="handleBeforeUpload"
          :auto-upload="false"
          :limit="1"
          :on-exceed="handleExceedByCreate"
        >
          <el-button type="primary">选取文件</el-button>
        </el-upload> -->
        <div class="mt-4">
          <el-input
            v-model="standardForm.filePath"
            placeholder="请选择文件路径"
          >
            <template #append>
              <el-button :icon="DocumentAdd" @click="proxySelectFile" />
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="基准分类 :">
        <el-input
          v-model="standardForm.clsKey"
          readonly
          class="read-only-input"
        />
      </el-form-item>
      <!-- 这个prop必须写，不然表单校验不会生效，下面的字段也一样 -->
      <!-- <el-form-item label="标题1 :" prop="title1">
        <el-input v-model="standardForm.title1" />
      </el-form-item>
      <el-form-item label="标题2 :" prop="title2">
        <el-input v-model="standardForm.title2" />
      </el-form-item>
      <el-form-item label="标题3 :" prop="title3">
        <el-input v-model="standardForm.title3" />
      </el-form-item>
      <el-form-item label="标题4 :" prop="title4">
        <el-input v-model="standardForm.title4" />
      </el-form-item> -->
      <!-- 4个标题一起在这里 -->
      <el-form-item label="标题1 :" prop="title1">
        <el-select
          v-model="standardForm.title1"
          placeholder="下拉选择"
          filterable
          allow-create
        >
          <el-option
            v-for="item in listOfValueCache.PP8_TITLE1"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题2 :" prop="title2">
        <el-select
          v-model="standardForm.title2"
          placeholder="下拉选择"
          filterable
          allow-create
        >
          <el-option
            v-for="item in listOfValueCache.PP8_TITLE2"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题3 :" prop="title3">
        <el-select
          v-model="standardForm.title3"
          placeholder="下拉选择"
          filterable
          allow-create
        >
          <el-option
            v-for="item in listOfValueCache.PP8_TITLE3"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标题4 :" prop="title4">
        <el-select
          v-model="standardForm.title4"
          placeholder="下拉选择"
          filterable
          allow-create
        >
          <el-option
            v-for="item in listOfValueCache.PP8_TITLE4"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="管理番号 :" prop="guanliFanHao">
        <el-input v-model="standardForm.guanliFanHao" />
      </el-form-item>
      <el-form-item label="文书名 :" prop="wenshuMing">
        <el-input v-model="standardForm.wenshuMing" />
      </el-form-item>
      <el-form-item label="公开标准 :">
        <el-input v-model="standardForm.gongKaiBiaoZhun" />
      </el-form-item>
      <el-form-item label="承认标准 :">
        <el-input v-model="standardForm.chengRenBiaoZhun" />
      </el-form-item>
      <el-form-item label="英语化 :">
        <el-switch v-model="standardForm.yingYuHua" />
      </el-form-item>
      <el-form-item label="中文化 :">
        <el-switch v-model="standardForm.zhongWenHua" />
      </el-form-item>
      <el-form-item label="适用性 :">
        <el-input v-model="standardForm.shiYongXing" />
      </el-form-item>
      <el-form-item label="工厂 :">
        <el-input v-model="standardForm.gongChang" />
      </el-form-item>
      <el-form-item label="商品别 :" prop="shangPinBie">
        <el-select
          v-model="standardForm.shangPinBie"
          placeholder="下拉选择"
          filterable
          allow-create
        >
          <el-option
            v-for="item in productList"
            :key="item"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="制定日 :">
        <el-input
          v-model="standardForm.zhiDingRi"
          readonly
          class="read-only-input"
        />
      </el-form-item>
      <el-form-item label="作成者 :">
        <el-input
          v-model="standardForm.zuoChengZhe"
          readonly
          class="read-only-input"
        />
      </el-form-item>
      <el-form-item label="制定理由">
        <el-checkbox
          v-for="item in standardForm.zhiDingLiYou"
          :key="item.name"
          :label="item.name"
          v-model="item.checked"
        />
      </el-form-item>
      <el-form-item label="关联规格法规">
        <el-checkbox
          v-for="item in standardForm.guanLianGuiGeFaGui"
          :key="item.name"
          :label="item.name"
          v-model="item.checked"
        />
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="submitCreateForm">确定</el-button>
      </el-form-item> -->
    </el-form>
  </el-drawer>
  <el-drawer v-model="viewDrawer" title="基准属性" :direction="viewDrawerDir">
    <el-form
      :model="standardForm"
      label-width="100px"
      label-position="left"
      ref="standardFormRef"
    >
      <el-form-item label="公开标准 :">
        <el-input v-model="standardForm.gongKaiBiaoZhun" readonly />
      </el-form-item>
      <el-form-item label="承认标准 :">
        <el-input v-model="standardForm.chengRenBiaoZhun" readonly />
      </el-form-item>
      <el-form-item label="英语化 :">
        <el-switch v-model="standardForm.yingYuHua" disabled />
      </el-form-item>
      <el-form-item label="中文化 :">
        <el-switch v-model="standardForm.zhongWenHua" disabled />
      </el-form-item>
      <el-form-item label="适用性 :">
        <el-input v-model="standardForm.shiYongXing" readonly />
      </el-form-item>
      <el-form-item label="工厂 :">
        <el-input v-model="standardForm.gongChang" readonly />
      </el-form-item>
      <el-form-item label="商品别 :">
        <el-input v-model="standardForm.shangPinBie" readonly />
      </el-form-item>
      <el-form-item label="管理番号 :">
        <el-input v-model="standardForm.guanliFanHao" readonly />
      </el-form-item>
      <el-form-item label="文书名 :">
        <el-input v-model="standardForm.wenshuMing" readonly />
      </el-form-item>
      <el-form-item label="制定日 :">
        <el-input v-model="standardForm.zhiDingRi" readonly />
      </el-form-item>
      <el-form-item label="作成者 :">
        <el-input v-model="standardForm.zuoChengZhe" readonly />
      </el-form-item>
      <el-form-item label="检印者 :">
        <el-input v-model="standardForm.jianYinZhe" readonly />
      </el-form-item>
      <el-form-item label="承认者 :">
        <el-input v-model="standardForm.chengRenZhe" readonly />
      </el-form-item>
      <el-form-item label="发布状态 :">
        <el-input v-model="standardForm.fabuZhuangTai" readonly />
      </el-form-item>
      <el-form-item label="制定理由">
        <el-checkbox
          v-for="item in standardForm.zhiDingLiYou"
          :key="item.name"
          :label="item.name"
          v-model="item.checked"
          disabled
        />
      </el-form-item>
      <el-form-item label="关联规格法规">
        <el-checkbox
          v-for="item in standardForm.guanLianGuiGeFaGui"
          :key="item.name"
          :label="item.name"
          v-model="item.checked"
          disabled
        />
      </el-form-item>
      <el-form-item label="订正日 :">
        <el-input v-model="standardForm.dingZhengRi" readonly />
      </el-form-item>
      <el-form-item label="订正No. :">
        <el-input v-model="standardForm.dingZhengNo" readonly />
      </el-form-item>
      <el-form-item label="订正理由 :">
        <el-input v-model="standardForm.dingZhengLiYou" readonly />
      </el-form-item>
      <!-- <el-form-item>
        <el-button type="primary" @click="submitForm">保存</el-button>
      </el-form-item> -->
    </el-form>
  </el-drawer>
  <el-drawer
    v-model="standardReviseDrawer"
    title="基准修订"
    direction="ltr"
    :show-close="false"
  >
    <template #header="{ close, titleId, titleClass }">
      <h4 :id="titleId" :class="titleClass">基准修订</h4>
      <el-button type="primary" @click="submitReviseForm">确定</el-button>
      <el-button type="danger" @click="close">关闭</el-button>
    </template>
    <el-form
      :model="standardForm"
      label-width="100px"
      label-position="left"
      :rules="reviseFormRules"
      ref="standardFormRef"
    >
      <el-form-item label="附件 :" prop="filePath">
        <div class="mt-4">
          <el-input
            v-model="standardForm.filePath"
            placeholder="请选择文件路径"
          >
            <template #append>
              <el-button :icon="DocumentAdd" @click="proxySelectFile" />
            </template>
          </el-input>
        </div>
      </el-form-item>
      <el-form-item label="基准分类 :">
        <el-input
          v-model="standardForm.clsKey"
          readonly
          class="read-only-input"
        />
      </el-form-item>
      <!-- 这个prop必须写，不然表单校验不会生效，下面的字段也一样 -->
      <el-form-item
        label="管理番号 :"
        prop="guanliFanHao"
        class="read-only-input"
        readonly
      >
        <el-input v-model="standardForm.guanliFanHao" />
      </el-form-item>
      <el-form-item label="文书名 :" prop="wenshuMing">
        <el-input v-model="standardForm.wenshuMing" />
      </el-form-item>
      <el-form-item label="订正日 :">
        <el-input
          v-model="standardForm.dingZhengRi"
          readonly
          class="read-only-input"
        />
      </el-form-item>
      <el-form-item label="订正号 :">
        <el-input v-model="standardForm.dingZhengNo" />
      </el-form-item>
      <el-form-item label="订正理由 :" prop="dingZhengLiYou">
        <el-input v-model="standardForm.dingZhengLiYou" />
      </el-form-item>
      <el-form-item label="公开标准 :">
        <el-input v-model="standardForm.gongKaiBiaoZhun" />
      </el-form-item>
      <el-form-item label="承认标准 :">
        <el-input v-model="standardForm.chengRenBiaoZhun" />
      </el-form-item>
      <el-form-item label="英语化 :">
        <el-switch v-model="standardForm.yingYuHua" />
      </el-form-item>
      <el-form-item label="中文化 :">
        <el-switch v-model="standardForm.zhongWenHua" />
      </el-form-item>
      <el-form-item label="适用性 :">
        <el-input v-model="standardForm.shiYongXing" />
      </el-form-item>
      <el-form-item label="工厂 :">
        <el-input v-model="standardForm.gongChang" />
      </el-form-item>
      <el-form-item label="商品别 :">
        <el-input v-model="standardForm.shangPinBie" />
      </el-form-item>
    </el-form>
  </el-drawer>
  <el-drawer v-model="attachmentDrawer" title="附件列表" :with-header="true">
    <el-table :data="attachmentData" style="width: 100%">
      <el-table-column prop="datasetName" label="名称" align="center" />
      <el-table-column prop="dataset_type" label="类型" align="center" />
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <!-- 这里放置您想要在最后一列展示的内容 -->
          <el-button type="primary" @click="watchContent2(row.datasetUid)">
            打开
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-drawer>
</template>

<style>
.input-with-select .el-input-group__prepend {
  background-color: var(--el-fill-color-blank);
}

.input-with-select {
  width: 400px;
}

.split-pane {
  display: flex;
  height: 100vh;
}

.read-only-input .el-input__inner {
  background-color: #f5f5f5;
}

.read-only-input .el-input__wrapper {
  background-color: #f5f5f5;
}

.left-pane,
.right-pane {
  flex: 1;
  overflow: auto;
}

.left-pane {
  background-color: lightblue;
}

.right-pane {
  background-color: lightcoral;
}

.drag-handle {
  cursor: ew-resize;
  background-color: #ccc;
  width: 5px;
}

.ghost {
  opacity: 0.5;
}

.chosen {
  background-color: #f9f9f9;
}

.drag {
  background-color: #f9f9f9;
}

.breadcrumb-link {
  color: blue;
  text-decoration: underline;
  cursor: pointer;
}
</style>
<!-- <script>
export default {
  mounted: function () {
    this.$nextTick(() => {
      (this.$refs.docTree as any).setCurrentKey("");
    });
  },
};
</script> -->
<script lang="ts" setup>
import {
  UploadProps,
  UploadUserFile,
  UploadInstance,
  ElMessage,
  ElMessageBox,
  genFileId,
} from "element-plus";
import {
  ref,
  getCurrentInstance,
  nextTick,
  Ref,
  reactive,
  computed,
  watch,
} from "vue";
import {
  Search,
  ArrowRight,
  DocumentAdd,
  Delete,
} from "@element-plus/icons-vue";
import { onMounted } from "vue";
import { useRouter } from "vue-router";
import { ElTree } from "element-plus";
import { collapseContextKey } from "element-plus";
import JxBrowserUtil from "@/utils/JxBrowserUtil";

import type { ElForm } from "element-plus";
import { FormInstance } from "element-plus";
import { TableInstance } from "element-plus";

const instance = getCurrentInstance();
const { $http } = instance?.appContext.config.globalProperties as any;
const jxBrowserUtil = new JxBrowserUtil();

const docTable = ref(TableInstance);
const total = ref();
const currentPage = ref(0);
const pageSize = ref(20);
// const isUnreleased = ref(true);
// const isReleased = ref(true);
// const isObsolete = ref(false);

const checkedStatus = ref(["未发布", "承认"]);
const statusList = ["未发布", "承认", "废弃"];

const docTree = ref(null);

const viewDrawerDir = ref("rtl");

const viewDrawer = ref(false);

const createDrawer = ref(false);

const standardReviseDrawer = ref(false);

const leftPanelWidth = ref(300); // 初始左边面板宽度

const input2 = ref("");

const currentNodeKey = ref("");

const currentNodeName = ref("");

const isCurrentNodeLeaf = ref(true);

const currentTableRow = ref();

const userName = ref("");

const isManager = ref(true);

const productList = ref([]);

let selPaths = ref<string[]>();

const debounce = (
  callback: { apply: (arg0: any, arg1: any[]) => void },
  delay: number | undefined
) => {
  let tid: number | undefined;
  return function (...args: any) {
    tid && clearTimeout(tid);
    tid = setTimeout(() => {
      callback.apply(getCurrentInstance(), args);
    }, delay);
  };
};

const _ = window.ResizeObserver;
window.ResizeObserver = class ResizeObserver extends _ {
  constructor(callback: any) {
    callback = debounce(callback, 20);
    super(callback);
  }
};

onMounted(() => {
  // jxBrowserUtil.proxyFunc(window, setUserInfoFromPLM, "setUserInfoFromPLM");
  (window as any).setProxySelectedFilePath = setProxySelectedFilePath;
  (window as any).proxyError = proxyError;
  (window as any).proxyInfo = proxyInfo;
  (window as any).onProxyCreateCompleted = onProxyCreateCompleted;
  // 获取传递的参数
  const router = useRouter();
  let name = router.currentRoute.value.query.docType;
  let user_name = router.currentRoute.value.query.userName as string;
  let manager_flag = router.currentRoute.value.query.manager;
  isManager.value = "true" == manager_flag;
  console.log("传递过来的参数是 ", name, user_name, manager_flag);
  userName.value = user_name;
  //currentNodeKey.value = name == null ? "" : name.toString();
  loadTreeData(name == null ? "" : name.toString());
  loadProductList();
  // const ret = findLabelPath(treeData.value, currentNodeKey.value);
  // console.log(ret);
  // let paths: string[] = [];

  // ret?.forEach((r) => {
  //   paths.push(r.label);
  // });
  // console.log("paths = ", paths);
  // selPaths.value = paths;
  // search();
});

// const setUserInfoFromPLM = (user_id: string, user_name: string) => {
//   console.log("读取到用户信息${user_id}, ${user_name}");
//   userId.value = user_id;
//   userName.value = user_name;
// };
const loadProductList = () => {
  const url = "/getProductListOfValues";
  $http
    .get(url)
    .then((response: { data: any }) => {
      console.log("查询结果", response.data);
      productList.value = response.data;
    })
    .catch((error: any) => {
      console.log(error);
    });
};

const breadcrumbHandle = (path: string) => {
  console.log(path);
  currentNodeKey.value = path;
  currentNodeName.value = path;
  //loadTreeData(path);
  let docTreeValue = docTree.value as any;
  console.log(docTreeValue.root.data[0].label);
  console.log(docTreeValue.root.data[0].id);
  // if (
  //   path === docTreeValue.root.data[0].label
  // ) {
  //   console.log("返回首页");
  //   window.history.back();
  // } else {
  //   //触发docTree的更新事件
  //   docTreeValue.setCurrentKey(path);
  // }
  if ("主页" === path) {
    window.history.back();
  } else {
    //触发docTree的更新事件
    docTreeValue.setCurrentKey(path);
  }
};

function findLabelPath(
  tree: any[],
  targetLabel: string,
  path: any[] = []
): any[] | null {
  console.log("查找匹配的树节点：" + targetLabel);
  for (const node of tree) {
    path.push(node);
    if (node.label === targetLabel) {
      console.log("匹配成功！");
      return path;
    }

    if (node.children) {
      const found = findLabelPath(node.children, targetLabel, path);
      if (found) {
        return found;
      }
    }

    path.pop();
  }

  return null;
}

const proxySelectFile = () => {
  (window as any).java.getSelectedFile();
};

const setProxySelectedFilePath = (filePath: string) => {
  console.log("setProxySelectedFilePath = ", filePath);
  standardForm.filePath = filePath;
};

const proxyError = (errorMsg: string) => {
  ElMessage({
    type: "error",
    message: errorMsg,
  });
};

const proxyInfo = (info: string, type: string, isReload: boolean) => {
  ElMessage({
    type: type,
    message: info,
  });
  if (isReload) {
    loadTreeData(currentNodeName.value);
  }
};

const onProxyCreateCompleted = (uid: string) => {
  console.log("completed");
  // ElMessage({
  //   type: "info",
  //   message: "创建成功",
  // });
  // let flag = ElMessageBox.confirm(`创建成功，是否立即发起审批流程 ?`).then(
  //   () => true,
  //   () => false
  // );
  // if (flag) {
  //   (window as any).java.createWorkflow(uid);
  // }
  ElMessageBox.confirm(`创建成功，是否立即发起审批流程 ?`)
    .then(() => {
      (window as any).java.createWorkflow(uid);
      createDrawer.value = false;
      standardReviseDrawer.value = false;
    })
    .catch(() => {
      ElMessage({
        type: "success",
        message: "完成",
      });
      createDrawer.value = false;
      standardReviseDrawer.value = false;
    });
  loadTreeData(currentNodeName.value);
};

const createWorkflow = () => {
  console.log(currentTableRow);
  (window as any).java.createWorkflow(currentTableRow.value.PUID);
};

const fileList = ref([]);

const fileListByCreate = ref([]);

// const handleRemove = (file: any, uploadFiles: any) => {
//   console.log(file, uploadFiles);
// };

// const handlePreview = (uploadFile: any) => {
//   console.log(uploadFile);
// };

const uploadByRevise = ref(UploadInstance);
const uploadByCreate = ref(UploadInstance);

const handleExceedByRevise = (files: any[]) => {
  uploadByRevise.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadByRevise.value!.handleStart(file);
};
const handleExceedByCreate = (files: any[]) => {
  uploadByCreate.value!.clearFiles();
  const file = files[0];
  file.uid = genFileId();
  uploadByCreate.value!.handleStart(file);
};

const handleBeforeUpload = (file: any) => {
  // 获取所选文件的路径
  console.log("来了");
  console.log("文件路径:", file);
  // 如果需要将路径存储到组件的数据中，可以将其赋值给组件的属性
  // this.filePath = file.raw.path;
  // 返回 false 阻止上传
  let json = JSON.stringify(file);
  console.log("json:", json);
  (window as any).java.uploadFile2(file.raw);
  return false;
};

const beforeRemove = (uploadFile: { name: any }, uploadFiles: any) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};

const standardForm = reactive({
  clsPath: "",
  clsKey: "",
  filePath: "",
  title1: "",
  title2: "",
  title3: "",
  title4: "",
  gongKaiBiaoZhun: "",
  chengRenBiaoZhun: "",
  yingYuHua: false,
  zhongWenHua: false,
  shiYongXing: "",
  gongChang: "",
  shangPinBie: "",
  guanliFanHao: "",
  wenshuMing: "",
  zhiDingRi: "",
  zuoChengZhe: "",
  jianYinZhe: "",
  chengRenZhe: "",
  zhiDingLiYou: [
    { name: "法规", checked: false },
    { name: "安全性", checked: false },
    { name: "耐久性", checked: false },
    { name: "加工", checked: false },
    { name: "市场", checked: false },
    { name: "信赖性", checked: false },
    { name: "组立上", checked: false },
    { name: "其它", checked: false },
  ],
  guanLianGuiGeFaGui: [
    { name: "JIS", checked: false },
    { name: "MIS", checked: false },
    { name: "其它", checked: false },
  ],
  dingZhengRi: "",
  dingZhengNo: "",
  dingZhengLiYou: "",
  fabuZhuangTai: "",
});

const createFormRules = ref({
  filePath: [{ required: true, message: "文件不得为空", trigger: "blur" }],
  // title1: [{ required: true, message: "标题1不得为空", trigger: "blur" }],
  // title2: [
  //   {
  //     required: true,
  //     message: "标题2不得为空",
  //     trigger: "blur",
  //   },
  // ],
  // title3: [
  //   {
  //     required: true,
  //     message: "标题3不得为空",
  //     trigger: "blur",
  //   },
  // ],
  // title4: [
  //   {
  //     required: true,
  //     message: "标题4不得为空",
  //     trigger: "blur",
  //   },
  // ],
  guanliFanHao: [
    {
      required: true,
      message: "管理番号不得为空",
      trigger: "blur",
    },
  ],
  wenshuMing: [
    {
      required: true,
      message: "文书名不得为空",
      trigger: "blur",
    },
  ],
});

const reviseFormRules = ref({
  wenshuMing: [
    {
      required: true,
      message: "文书名不得为空",
      trigger: "blur",
    },
  ],
  dingZhengLiYou: [
    {
      required: true,
      message: "订正理由不得为空",
      trigger: "blur",
    },
  ],
});

const standardFormRef = ref(FormInstance);

const submitForm = () => {
  standardFormRef.value.validate((valid: any) => {
    if (valid) {
      // 表单验证通过，执行提交操作
      console.log("表单验证通过，提交数据：", standardForm);
    } else {
      // 表单验证失败
      return false;
    }
  });
};

const submitCreateForm = () => {
  // uploadByCreate.value!.submit();
  standardFormRef.value.validate((valid: any) => {
    if (valid) {
      // 表单验证通过，执行提交操作
      console.log("表单验证通过，提交数据：", valid, standardForm);
      let json = JSON.stringify(standardForm);
      console.log(json);
      // let file = fileListByCreate.value;
      // console.log("待上传的文件为：", file);
      (window as any).java.createStandardDoc(json);
    } else {
      // 表单验证失败
      return false;
    }
  });
};

const submitReviseForm = () => {
  // uploadByCreate.value!.submit();
  standardFormRef.value.validate((valid: any) => {
    if (valid) {
      // 表单验证通过，执行提交操作
      console.log("表单验证通过，提交数据：", valid, standardForm);
      let json = JSON.stringify(standardForm);
      console.log(json);
      // let file = fileListByCreate.value;
      // console.log("待上传的文件为：", file);
      (window as any).java.reviseStandardDoc(json);
    } else {
      // 表单验证失败
      return false;
    }
  });
};

const loadTreeData = (selNodeName: string) => {
  currentNodeName.value = selNodeName;
  const url = "/getStandardClassification";
  $http
    .get(url)
    .then((response: { data: any }) => {
      console.log("查询结果", response.data);
      treeData.value = response.data;
      const ret = findLabelPath(treeData.value, selNodeName);
      console.log("匹配结果" + ret);
      let paths: string[] = [];
      ret?.forEach((r) => {
        paths.push(r.label);
      });
      console.log("paths = ", paths);
      console.log("node = " + selNodeName);
      setTimeout(() => {
        selPaths.value = paths;
        currentNodeKey.value = selNodeName;
        search(selNodeName, undefined);
      }, 1);
    })
    .catch((error: any) => {
      console.log(error);
    });
};
// const loadTreeData = async () => {
//   try {
//     const url = "/getStandardClassification";
//     const response = await $http.get(url);
//     console.log("查询结果", response.data);
//     treeData.value = response.data;
//   } catch (error) {
//     console.log(error);
//   }
// };

const researchByFilterText = () => {
  let text = input2.value;
  search(currentNodeKey.value, text);
};

const handleCurrentChange = (val: any) => {
  let ps = pageSize.value;
  currentPage.value = val;
  let i = val - 1;
  // currentPageTableData.value = tableData.value.slice(i * ps, (i + 1) * ps);
  currentPageTableData.value = filteredTableData.value.slice(
    i * ps,
    (i + 1) * ps
  );
  console.log("==========================", val, ps);
  // console.log(tableData.value);
  // console.log(currentPageTableData.value);
};
const search = (typeName: string, filterText: string | undefined) => {
  console.log("search...");
  let url = "/getStandardsDocByTypeName?typeNames=" + typeName;
  console.log("filterText = " + filterText);
  if (filterText) {
    url += "&filterText=" + filterText;
  }
  if (checkedStatus.value.length > 0) {
    url += "&status=" + checkedStatus.value.join(",");
  }
  console.log("url = " + url);
  $http
    .get(url)
    .then((response: { data: any }) => {
      console.log("查询结果", response.data);
      // this.bomInfos = [response.data];
      // this.expand_row_keys = [this.bomInfos[0].child_item_revision_uid];
      tableData.value = response.data;
      filteredTableData.value = response.data;
      total.value = response.data == null ? 0 : response.data.length;
      handleCurrentChange(1);
      buildListOfValue();
      buildFilterListOfValue(0);
      clearFilter();
    })
    .catch((error: any) => {
      console.log(error);
    });
  // $http
  //   .get(url)
  //   .then((response: any) => {
  //     console.log("search end.");
  //     console.log(response);
  //   })
  //   .catch((error: any) => {
  //     console.error(error);
  //   });
};

// const filterHandler = (value: string, row: any, column: any) => {
//   const property = column.columnConfig;
//   console.log("过滤：" + column);
//   console.log(row);
//   // return row[property] === value;
// };

const needLoadLovPropNames = [
  "PP8_TITLE1",
  "PP8_TITLE2",
  "PP8_TITLE3",
  "PP8_TITLE4",
];

const listOfValueCache = ref();
const columnFilters: { [key: string]: any } = ref({
  PP8_TITLE1: [],
  PP8_TITLE2: [],
  PP8_TITLE3: [],
  PP8_TITLE4: [],
});

const buildListOfValue = () => {
  console.log("buildListOfValue --> ", tableData);
  listOfValueCache.value = {};
  needLoadLovPropNames.forEach((propName) => {
    listOfValueCache.value[propName] = [];
  });

  tableData.value.forEach((data) => {
    needLoadLovPropNames.forEach((propName) => {
      if (!listOfValueCache.value[propName].includes(data[propName])) {
        listOfValueCache.value[propName].push(data[propName]);
      }
    });
  });
  // console.log(listOfValueCache.value);
};
const buildFilterListOfValue = (index: number) => {
  // needLoadLovPropNames.forEach((propName) => {
  //   columnFilters.value[propName] = [];
  // });

  for (let i = index; i < needLoadLovPropNames.length; i++) {
    const propName = needLoadLovPropNames[i];
    columnFilters.value[propName] = [];
  }

  //传入0就用全数据，大于0的时候用过滤的数据
  // let useData = index == 0 ? tableData.value : filteredTableData.value;
  let useData = filteredTableData.value;
  useData.forEach((data) => {
    for (let i = index; i < needLoadLovPropNames.length; i++) {
      const propName = needLoadLovPropNames[i];
      if (
        !columnFilters.value[propName].some(
          (item: { value: any }) => item.value === data[propName]
        )
      ) {
        columnFilters.value[propName].push({
          text: data[propName],
          value: data[propName],
        });
      }
    }
    // needLoadLovPropNames.forEach((propName) => {
    //   if (
    //     !columnFilters.value[propName].some(
    //       (item: { value: any }) => item.value === data[propName]
    //     )
    //   ) {
    //     columnFilters.value[propName].push({
    //       text: data[propName],
    //       value: data[propName],
    //     });
    //   }
    // });
  });
  // console.log(listOfValueCache.value);
};

const deleteSelData = () => {
  ElMessageBox.confirm(`删除的数据无法恢复，请谨慎操作，是否继续 ?`)
    .then(() => {
      let item = currentTableRow.value;
      (window as any).java.deleteComponent(item.PUID);
    })
    .catch(() => {
      console.log("取消删除操作");
    });
};

const createDoc = () => {
  if (!isCurrentNodeLeaf.value) {
    ElMessage({
      type: "error",
      message: "所选阶段不允许创建新的文档",
    });
    return;
  }
  let clsPath = selPaths.value?.join(",");
  const currentDate = new Date();
  const currentDateTimeString = currentDate.toLocaleString();
  fileListByCreate.value = [];
  standardForm.clsPath = clsPath ? clsPath : "";
  standardForm.clsKey = currentNodeName.value;
  standardForm.filePath = "";
  standardForm.title1 = "";
  standardForm.title2 = "";
  standardForm.title3 = "";
  standardForm.title4 = "";
  standardForm.gongKaiBiaoZhun = "";
  standardForm.chengRenBiaoZhun = "";
  standardForm.yingYuHua = false;
  standardForm.zhongWenHua = false;
  standardForm.gongChang = "";
  standardForm.shangPinBie = "";
  standardForm.guanliFanHao = "";
  standardForm.wenshuMing = "";
  standardForm.zhiDingRi = currentDateTimeString; //当前时间
  standardForm.zuoChengZhe = userName.value; //传入的用户
  standardForm.jianYinZhe = "";
  standardForm.chengRenZhe = "";
  // standardForm.zhiDingLiYou = [item.MAKEREASON];
  // standardForm.guanLianGuiGeFaGui = "";
  standardForm.dingZhengRi = "";
  standardForm.dingZhengNo = "";
  standardForm.dingZhengLiYou = "";
  standardForm.fabuZhuangTai = "";
  standardForm.guanLianGuiGeFaGui.forEach((f) => {
    f.checked = false;
  });
  standardForm.zhiDingLiYou.forEach((f) => {
    f.checked = false;
  });
  createDrawer.value = true;
};

const reviseDoc = () => {
  const currentDate = new Date();
  const currentDateTimeString = currentDate.toLocaleString();
  console.log(currentTableRow);
  console.log(standardForm.guanLianGuiGeFaGui);
  let item = currentTableRow.value;
  let clsPath = selPaths.value?.join(",");
  standardForm.clsPath = clsPath ? clsPath : "";
  standardForm.clsKey = currentNodeName.value;
  standardForm.filePath = "";
  standardForm.gongKaiBiaoZhun = item.PP8_PUBLIC;
  standardForm.chengRenBiaoZhun = item.PP8_ACCEPT;
  standardForm.yingYuHua = item.PP8_ENGLISH && item.PP8_ENGLISH.length > 0;
  standardForm.zhongWenHua = item.PP8_CHINESE && item.PP8_CHINESE.length > 0;
  standardForm.gongChang = item.PP8_FACTORY;
  standardForm.shangPinBie = item.PP8_PRODUCT;
  standardForm.guanliFanHao = item.PITEM_ID;
  standardForm.wenshuMing = item.POBJECT_NAME;
  // standardForm.guanLianGuiGeFaGui = item.PP8_REFERENCELAW;
  // standardForm.zhiDingRi = item.PP8_CREATEDATE;
  // standardForm.zuoChengZhe = item.PP8_AUTHOR;
  // standardForm.jianYinZhe = item.PP8_CHECKOWNER;
  // standardForm.chengRenZhe = item.PP8_ACCEPTOR;
  // standardForm.zhiDingLiYou = [item.MAKEREASON];
  // standardForm.guanLianGuiGeFaGui = ""
  standardForm.dingZhengRi = currentDateTimeString;
  standardForm.dingZhengNo = "";
  standardForm.dingZhengLiYou = "";
  // standardForm.fabuZhuangTai = item.RELEASED_STATUS;
  standardForm.guanLianGuiGeFaGui.forEach((f) => {
    item.checked =
      item.PP8_REFERENCELAW && item.PP8_REFERENCELAW.includes(f.name);
  });
  standardForm.zhiDingLiYou.forEach((f) => {
    item.checked = item.PP8_MAKEREASON && item.PP8_MAKEREASON.includes(f.name);
  });
  standardReviseDrawer.value = true;
};

const watchProps = (item: any) => {
  console.log(item);
  console.log(item.PP8_PUBLIC);
  standardForm.gongKaiBiaoZhun = item.PP8_PUBLIC;
  standardForm.chengRenBiaoZhun = item.PP8_ACCEPT;
  standardForm.yingYuHua = item.PP8_ENGLISH && item.PP8_ENGLISH.length > 0;
  standardForm.zhongWenHua = item.PP8_CHINESE && item.PP8_CHINESE.length > 0;
  standardForm.gongChang = item.PP8_FACTORY;
  standardForm.shangPinBie = item.PP8_PRODUCT;
  standardForm.guanliFanHao = item.PITEM_ID;
  standardForm.wenshuMing = item.POBJECT_NAME;
  standardForm.zhiDingRi = item.PP8_CREATEDATE;
  standardForm.zuoChengZhe = item.PP8_AUTHOR;
  standardForm.jianYinZhe = item.PP8_CHECKOWNER;
  standardForm.chengRenZhe = item.PP8_ACCEPTOR;
  // standardForm.zhiDingLiYou = [item.MAKEREASON];
  // standardForm.guanLianGuiGeFaGui = ""
  standardForm.dingZhengRi = item.PP8_UPDATEDATE;
  standardForm.dingZhengNo = "";
  standardForm.dingZhengLiYou = item.PP8_UPDATEREASON;
  standardForm.fabuZhuangTai = item.RELEASED_STATUS;
  standardForm.guanLianGuiGeFaGui.forEach((f) => {
    item.checked =
      item.PP8_REFERENCELAW && item.PP8_REFERENCELAW.includes(f.name);
  });
  standardForm.zhiDingLiYou.forEach((f) => {
    item.checked = item.PP8_MAKEREASON && item.PP8_MAKEREASON.includes(f.name);
  });
  viewDrawer.value = true;
  viewDrawerDir.value = "rtl";
};

const watchContent = (item: any) => {
  console.log(item);
  console.log(instance?.appContext.config.globalProperties.$baseURL);
  window.open(
    instance?.appContext.config.globalProperties.$baseURL +
      "/openDatasetByRevUid?uid=" +
      item.PUID,
    "_blank"
  );
};
const watchContent2 = (item: string) => {
  //console.log(item);
  //console.log(instance?.appContext.config.globalProperties.$baseURL);
  //window.open(
  //instance?.appContext.config.globalProperties.$baseURL +
  //  "/openDatasetByRevUid?uid=" +
  //  item,
  //"_blank"
  // );
  jxBrowserUtil.openDataset(window, item);
};

const rowDoubleClick = (item: any) => {
  watchContent(item);
};

const onTreeCurrentChange = (data: any, node: any) => {
  //console.log(data, node);
  isCurrentNodeLeaf.value = node.isLeaf;
  currentNodeName.value = node.data.label;
  currentNodeKey.value = node.data.id;
  let paths: string[] = [];
  let curNode = node;
  do {
    paths.unshift(curNode.data.label);
    curNode = curNode.parent;
  } while (
    curNode != null &&
    curNode != undefined &&
    curNode.data.label != undefined
  );
  console.log("path is ", paths);
  selPaths.value = paths;
  let leafs = getAllChildrenLeaf(node);
  console.log("leafs = ", leafs);
  if (leafs == null || leafs.length == 0) return;
  let labels = leafs.map((leaf) => leaf.data.label);
  console.log("labels = ", labels);
  let labelJoin = labels.join(",");
  labelJoin = encodeURIComponent(labelJoin);
  search(labelJoin, undefined);
};

const getAllChildrenLeaf = (node: any) => {
  console.log("=>", node);
  let result: any[] | undefined = [];
  loadAllChildrenLeaf(node, result);
  return result;
};

const loadAllChildrenLeaf = (node: any, result: any[] = []) => {
  if (node.isLeaf) {
    result.push(node);
  } else {
    node.childNodes.forEach((childNode: any) => {
      loadAllChildrenLeaf(childNode, result);
    });
  }
};

const onTableCurrentChange = (data: any) => {
  console.log(data);
  currentTableRow.value = data;
};

const isTableSelRevisable = () => {
  return currentTableRow.value && currentTableRow.value.RELEASED_STATUS;
};

const isTableSelReleasable = () => {
  return currentTableRow.value && !currentTableRow.value.RELEASED_STATUS;
};

watch(checkedStatus, (newValue, oldValue) => {
  researchByFilterText();
});

const clearFilter = () => {
  docTable.value.clearFilter();
  filterOption.value = {};
  rebuildFilteredTableData();
};

const rebuildFilteredTableData = () => {
  // 根据过滤条件对tableData进行过滤
  filteredTableData.value = tableData.value.filter((item) => {
    // 这里假设过滤条件是一个函数，您可以根据实际情况调整
    //return filterCondition(item);
    // console.log("过滤 ： ", item);

    if (!filterOption.value || filterOption.value.length == 0) {
      // console.log("无过滤配置");
      return true;
    }

    let allMatch = true;

    for (const key in filterOption.value) {
      let v1 = filterOption.value[key];
      //console.log("匹配属性：", key);
      let singleMatch = false;
      if (v1 && v1.length > 0) {
        for (const k2 in v1) {
          let v2 = v1[k2];
          //console.log("过滤值为：", v2, "，行值为：", item[key]);
          if (item[key] === v2) {
            singleMatch = true;
            break;
          }
        }
      } else {
        singleMatch = true;
      }

      if (!singleMatch) {
        allMatch = false;
        break;
      }
    }
    return allMatch;
  });
  handleCurrentChange(1);
};

const filterOption: { [key: string]: any } = ref({});

const tableFilterChange = (filter: any) => {
  // console.log(">>>>>>", filter);
  // for (const key in filter) {
  //   let value = filter[key];
  //   // console.log("key = ", key);
  //   // console.log("value = ", value);
  //   filterOption.value[key] = value;
  //   const index = needLoadLovPropNames.indexOf(value);
  //   break;
  // }

  const [key, value] = Object.entries(filter)[0];
  filterOption.value[key] = value;
  const index = needLoadLovPropNames.indexOf(key);
  console.log("过滤配置为：", filterOption.value);
  rebuildFilteredTableData();
  //过滤完成后，当前选中用来过滤的列后面的列过滤列表要重新加载，因为有些下拉值是一定没值的，不应该显示出来
  console.log("选择的下标是：" + index);
  if (index >= 0) {
    buildFilterListOfValue(index + 1);
  }
};

const startResize = () => {
  document.addEventListener("mousemove", resize);
  document.addEventListener("mouseup", stopResize);
};

const resize = (event: MouseEvent) => {
  leftPanelWidth.value = event.clientX;
};

const stopResize = () => {
  document.removeEventListener("mousemove", resize);
  document.removeEventListener("mouseup", stopResize);
};

const defaultProps = {
  children: "children",
  label: "label",
};

const tableData = ref([]);
const filteredTableData = ref([]);
const currentPageTableData = ref([]);
const treeData = ref([]);
const attachmentDrawer = ref(false);
interface target {
  datasetUid: string;
  datasetName: string;
  dataset_type: string;
  originalFileName: string;
}
const attachmentData = ref<target[]>([]);
const openAttachmentData = (item: any) => {
  console.log(item.PUID);
  attachmentDrawer.value = true;
  getTargets(item.PUID);
};
const getTargets = (uid: string) => {
  console.log("getStandardTargets");
  let url = "/getStandardTargets?uid=" + uid;
  console.log("url = " + url);
  $http
    .get(url)
    .then((response: { data: any }) => {
      console.log("查询结果", response.data);
      attachmentData.value = response.data;
    })
    .catch((error: any) => {
      console.log(error);
    });
};
</script>
